package com.mango.community.controller;

import com.google.code.kaptcha.Producer;
import com.mango.community.entity.User;
import com.mango.community.service.UserService;
import com.mango.community.util.CommunityConstant;
import com.mango.community.util.CommunityUtil;
import com.mango.community.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @Author:  MangoCookieMilk
 * @Date:     2020/7/22 19:56
 */
@Controller
public class LoginController implements CommunityConstant {
    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;
    /**
     * 注入验证码生成配置类
     */
    @Autowired
    private Producer kaptchaProducer;
    /**
     * 项目的访问路径
     */
    @Value("${server.servlet.context-path}")
    private String contentPath;
    @Autowired
    private RedisTemplate redisTemplate;

    /**到注册页面
     * @return
     */
    @GetMapping("/register")
    public String getRegisterPage(){
        return "/site/register";
    }

    @GetMapping("/login")
    public String getLoginPage(){
        return "/site/login";
    }

    @PostMapping("/register")
    public String register(Model model, User user){
        Map<String,Object> map = userService.register(user);
        if(map == null || map.isEmpty()){
            model.addAttribute("msg","注册成功，我们已经像你的邮箱发送了激活邮件，请尽快激活!");
            model.addAttribute("target","/index");
            //注册成功后跳转到返回结果页面，将消息带过去
            return "/site/operate-result";
        }else {
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            model.addAttribute("emailMsg",map.get("emailMsg"));
            return "/site/register";
        }
    }

    @GetMapping("/activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId") int userId,@PathVariable("code") String code){
        int activation = userService.activation(userId, code);
        if (activation == ACTIVATION_SUCCESS){
            model.addAttribute("msg","激活成功，你的账号已经可以正常使用了！");
            model.addAttribute("target","/login");
        }else if(activation == ACTIVATION_REPEAT){
            model.addAttribute("msg","无效操作，该账号已经激活过了！");
            model.addAttribute("target","/index");
        }else {
            model.addAttribute("msg","激活失败，激活码错误！");
            model.addAttribute("target","/index");
        }
        return "/site/operate-result";
    }

    /** 验证码生成
     * @param response
     */
    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response/*, HttpSession session*/){
        //生成验证码
        //根据配置类生成一个随机的验证码字符串
        String text = kaptchaProducer.createText();
        //根据这个字符串生成图片
        BufferedImage image = kaptchaProducer.createImage(text);
        //将验证码存入session
        /*session.setAttribute("kaptcha",text);*/
        //验证码的归属，临时凭证
        String kaptchaOwner = CommunityUtil.generateUUID();
        //将凭证存入cookie中
        Cookie cookie = new Cookie("kaptchaOwner",kaptchaOwner);
        //设置cookie的存活时间为60秒
        cookie.setMaxAge(60);
        //设置cookie的有效路径，整个项目都有效
        cookie.setPath(contentPath);
        //放到response中发送给客户端
        response.addCookie(cookie);
        //生成验证码的key
        String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        //将验证码存入redis 并且设置过期时间为60 秒
        redisTemplate.opsForValue().set(redisKey,text,60,TimeUnit.SECONDS);
        //将图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            //使用这个类将图片image用OutputStream 的方式以png格式输出为图片
            ImageIO.write(image,"png",os);
        } catch (IOException e) {
            logger.error("响应验证码信息失败！"+e.getMessage());
        }
    }

    /**
     * @param userName
     * @param password
     * @param code    验证码
     * @param rememberMe   记住我
     * @param model
     * @param response
     * @param kaptchaOwner
     * @return
     * 登录
     */
    @PostMapping("/login")
    public String login(String userName, String password, String code,
                        boolean rememberMe, Model model,/* HttpSession session,*/
                        HttpServletResponse response,@CookieValue("kaptchaOwner") String kaptchaOwner){
        /*String kaptcha = (String) session.getAttribute("kaptcha");*/
        String kaptcha = null;
        //判断凭证是否失效  如果不为空表示数据没有失效
        if(StringUtils.isNoneBlank(kaptchaOwner)){
            //拿到验证码的key
            String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
            //获取redis中的验证码
            kaptcha = (String) redisTemplate.opsForValue().get(redisKey);
        }
        //判断传来的验证码与session中的验证码是否一致（equalsIgnoreCase 比较字符串是不区分大小写） 在都不为空的情况下
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)){
            model.addAttribute("codeMsg","验证码错误！");
            return "/site/login";
        }
        //检查账号密码
        //判断是否是记住我状态，然后获取凭证的过期时间
        int expiredSeconds = rememberMe ?  REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(userName, password, expiredSeconds);
        if( map.containsKey("ticket")){
            //如果map中存在ticket证明生成了凭证 ，将这个凭证拿到放入cookie中
            Cookie cookie = new Cookie("ticket",map.get("ticket").toString());
            //设置cookie的生效路径，一般是整个项目内都可以使用
            cookie.setPath(contentPath);
            //设置cookie的存活时间，就是刚在在上面获取的到凭证过期时间
            cookie.setMaxAge(expiredSeconds);
            //将cookie放到response 中会在响应浏览器的时候带上cookie ，存在浏览器上，下次请求会带上这个cookie，用来做凭证比较
            //验证是否有登录的权限
            response.addCookie(cookie);
            //登录成功后，重定向到首页
            return "redirect:/index";
        }else {
            //map中没有ticket 证明没有生成凭证，有可能是用户名或者密码的问题，将这两个问题的返回描述传到前台页面显示即可
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            //回到登录页
            return "/site/login";
        }
    }

    @GetMapping("/logout")
    public String logout(@CookieValue("ticket") String ticket){
        userService.logout(ticket);
        return "redirect:/login";
    }
}
